package com.neusoft.nep.admin.controller;

import com.neusoft.nep.admin.entity.AqiTrendData;
import com.neusoft.nep.admin.entity.AqiData;
import com.neusoft.nep.common.AqiDataFileUtil;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.time.YearMonth;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MonthsTrendViewController {

    @FXML
    private TableView<AqiTrendData> trendTable;

    @FXML
    private TableColumn<AqiTrendData, String> monthColumn;
    @FXML
    private TableColumn<AqiTrendData, Integer> dataColumn;
    @FXML
    private TableColumn<AqiTrendData, Integer> excessColumn;

    @FXML
    public void initialize() {
        monthColumn.setCellValueFactory(new PropertyValueFactory<>("month"));
        dataColumn.setCellValueFactory(new PropertyValueFactory<>("data"));
        excessColumn.setCellValueFactory(new PropertyValueFactory<>("excessCount"));

        trendTable.setItems(loadAndAnalyzeAqiData());
    }

    private boolean isExcessivePollution(String level) {
        if (level == null || level.isEmpty()) {
            return false;
        }
        switch (level) {
            case "优":
            case "良":
                return false;
            case "轻度污染":
            case "中度污染":
            case "重度污染":
            case "严重污染":
                return true;
            default:
                return false;
        }
    }

    private ObservableList<AqiTrendData> loadAndAnalyzeAqiData() {
        Map<String, AqiTrendData> trendMap = new HashMap<>();

        List<AqiData> allAqiData = AqiDataFileUtil.readAqiDataFromFile();

        if (allAqiData.isEmpty()) {
            System.out.println("文件 fankui3.txt 中没有AQI数据可供统计。");
            return FXCollections.observableArrayList();
        }

        for (AqiData data : allAqiData) {
            String dateStr = data.getDate();
            if (dateStr == null || dateStr.length() < 7) {
                System.err.println("跳过无效日期格式的数据: " + dateStr);
                continue;
            }

            String month = dateStr.substring(0, 7);

            AqiTrendData trendData = trendMap.computeIfAbsent(month, k -> new AqiTrendData("2025.6",  0));

            trendData.setData(trendData.getData() + 1);

            if (isExcessivePollution(data.getLevel())) {
                trendData.setExcessCount(trendData.getExcessCount() + 1);
            }
        }

        ObservableList<AqiTrendData> trendList = FXCollections.observableArrayList();
        trendList.addAll(trendMap.values());

        trendList.sort((d1, d2) -> YearMonth.parse(d1.getMonth()).compareTo(YearMonth.parse(d2.getMonth())));

        System.out.println("AQI数据已按月份统计完成。总共统计到 " + trendList.size() + " 个月份的数据。");
        return trendList;
    }
}